package com.fuhe.chen.vendingmachine.common;

import com.fuhe.chen.vendingmachine.dao.ContainerDao;
import com.fuhe.chen.vendingmachine.dao.MachineDao;
import com.fuhe.chen.vendingmachine.pojo.Machine;
import com.fuhe.chen.vendingmachine.service.IBookOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 机器容量缓存
 * 首次查询使用数据库
 * 之后通过实时计算获得
 */
@Component
public class MachineCache implements CommandLineRunner {

    @Autowired
    MachineDao machineDao;

    @Autowired
    ContainerDao containerDao;

    @Autowired
    IBookOrderService bookOrderService;

    public static ConcurrentHashMap<Integer,Integer> machineCapacity = new ConcurrentHashMap<>();

    /**
     * 获取机器id对应机器剩余容量
     * 入口: 1.用户查询机器信息时
     *       2.用户预约订单下单前
     *       3.用户取消订单退款前
     *       4.管理员拒绝用户订单退款申请前
     * @param id
     * @return
     */
    public static Integer getCapacity(Integer id) {
        return machineCapacity.get(id);
    }

    /**
     * 设置机器id对应机器剩余容量
     * 入口:通过数据库查询容量后
     * @param id
     * @param capacity
     */
    public static void setCapacity(Integer id, Integer capacity) {
        machineCapacity.put(id,capacity);
    }

    /**
     * 设置对应机器剩余容量加1
     * 入口:1.预约订单申请退款,进入待退款状态
     *      2.机器无人售货模式售出货物
     *      3.预约订单取货成功,交易完成
     * @param machine_id
     */
    public static void addCapacity(Integer machine_id) {
        Integer capacity = getCapacity(machine_id);
        if(capacity!=null){
            capacity = capacity + 1 ;
            setCapacity(machine_id,capacity);
        }
    }

    /**
     * 设置对应机器剩余容量减1
     * 入口: 1.预约订单完成支付,进入待发货状态
     *       2.机器添加无人售货库存
     *       3.预约订单取消申请退款,进入待发货状态
     *       4.退款申请被驳回,进入待发货状态
     * @param machine_id
     */
    public static void reduceCapacity(Integer machine_id) {
        Integer capacity = getCapacity(machine_id);
        if(capacity!=null){
            capacity = capacity - 1 ;
            setCapacity(machine_id,capacity);
        }
    }

    @Override
    public void run(String... args) throws Exception {
        List<Machine> machines = machineDao.findAll();
        for (Machine machine : machines) {
            if (machine.getType()==0){
                Integer capacity = MachineCache.getCapacity(machine.getId());
                if(capacity==null){
                    //机器总容量 - 非空格子柜数 - 已付款的预约订单数
                    capacity = machine.getCapacity()- containerDao.getCapacity(machine.getId()) - bookOrderService.getBookCapacity(machine.getId());
                    setCapacity(machine.getId(),capacity);
                }
            }
        }
    }
}
